package com.explorer.ider.bootguide.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import com.explorer.ider.bootguide.MainActivity;
import com.explorer.ider.bootguide.R;
import com.explorer.ider.bootguide.adapter.AppSelectAdapter;
import com.explorer.ider.bootguide.itembean.ApkInfo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Eric on 2017/9/19.
 */

public class FragmentAppSelect extends Fragment {


    private View views;
    private ImageView imageView;
    private Button skip,selectNothingBtn;
    private Method systemProperties_get = null;
    private String sn;
    private Context context;
    private final String APPS_PATH="/system/preinstall1";
    private AppSelectAdapter appSelectAdapter;
    private List<ApkInfo>apkInfos;
    private List<String>apkPaths;
    private GridView appSelectGridView;



    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        context=getActivity();
        apkPaths = getApkFileNames(APPS_PATH);
        if (views == null){
            views = inflater.inflate(R.layout.fragment_app_select, container,false);
            imageView = (ImageView) views.findViewById(R.id.image_view);
            skip = (Button)views.findViewById(R.id.complete);

            skip.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toNextPager();
                }
            });
            selectNothingBtn=(Button) views.findViewById(R.id.select_nothing);//都不要
            selectNothingBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toNextPager();
                }
            });

//            final Animation mAnimationIn , mAnimationOut;
//            mAnimationIn = AnimationUtils.loadAnimation(getActivity(), R.anim.view_focus_animation_in);
//            mAnimationOut = AnimationUtils.loadAnimation(getActivity(),R.anim.view_focus_animation_out);
//            mAnimationIn.setFillAfter(true);
//            mAnimationOut.setFillAfter(true);
//            skip.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    if (hasFocus) {
//                        v.startAnimation(mAnimationIn);
//                    }else {
//                        v.startAnimation(mAnimationOut);
//                    }
//                }
//            });
//            selectAllBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    if (hasFocus) {
//                        v.startAnimation(mAnimationIn);
//                    }else {
//                        v.startAnimation(mAnimationOut);
//                    }
//                }
//            });
//            selectNothingBtn.setOnFocusChangeListener(new View.OnFocusChangeListener() {
//                @Override
//                public void onFocusChange(View v, boolean hasFocus) {
//                    if (hasFocus) {
//                        v.startAnimation(mAnimationIn);
//                    }else {
//                        v.startAnimation(mAnimationOut);
//                    }
//                }
//            });
            apkInfos=getApkinfos();
            appSelectGridView = (GridView) views.findViewById(R.id.app_select_grid_view);
            appSelectAdapter = new AppSelectAdapter(context,apkInfos);

            appSelectGridView.setAdapter(appSelectAdapter);
            appSelectGridView.setSelection(apkInfos.size()-1);


        }
        return views;
    }



    private List<ApkInfo> getApkinfos() {
        List<ApkInfo>apkInfos=new ArrayList<ApkInfo>();
        for (String string : apkPaths) {
            ApkInfo apkInfo=getApkInfo(string);
            apkInfos.add(apkInfo);
        }
        return apkInfos;
    }
    private ApkInfo getApkInfo(String apkPath){
        PackageManager pm = context.getPackageManager();
        PackageInfo pi = pm.getPackageArchiveInfo(apkPath, 0);
        ApplicationInfo appInfo = pi.applicationInfo;
        appInfo.sourceDir =apkPath;
        appInfo.publicSourceDir = apkPath;
        try {
            ApkInfo apkInfo = new ApkInfo(appInfo.loadIcon(pm), (String)appInfo.loadLabel(pm));
            return apkInfo;
        } catch (OutOfMemoryError e) {
            Log.d("------", "---"+e.toString());
        }
        return null;
    }



    public  List<String> getApkFileNames(String path) {
        List<String> vecFile = new ArrayList<String>();
        File file = new File(path);
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
            // 判断是否为文件夹
            if (!subFile[iFileLength].isDirectory()) {
                String filename = subFile[iFileLength].getName();
                // 判断是否为apk结尾
                if (filename.trim().toLowerCase().endsWith(".apk")) {
                    vecFile.add(APPS_PATH+"/"+filename);
                }
            }
        }
        return vecFile;
    }





    private String getFileRoot(Context context) {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = context.getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath();
            }
        }

        return context.getFilesDir().getAbsolutePath();
    }
    private String getAndroidOsSystemProperties(String key) {
        String ret;
        try {
            systemProperties_get = Class.forName("android.os.SystemProperties").getMethod("get", String.class);
            if ((ret = (String) systemProperties_get.invoke(null, key)) != null)
                return ret;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return "";
    }

    private void toNextPager(){
        Intent intent = new Intent();
        intent.setAction(MainActivity.ACTION_TO_NEXT_PAGER5);
        getActivity().sendBroadcast(intent);

    }

    public String getEthMac() {
        File file = new File("/sys/class/net/eth0/address");
        try {
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String mac = br.readLine();
            if (!mac.equals(""))
            Log.i("FragmentTwoDimen", mac);
            return mac;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

}
